package pos.server.dac;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alessio
 */
public class UniConnectionManager
{
    private UniConnectionManager()
    {
    }
    private static Connection conn;
    private static final String MY_DRIVER =
            "org.postgresql.Driver";
    private static String MY_URL =
            "jdbc:postgresql://?:5432/universita";
    private static final String LOGIN = "postgres";
    private static final String PASSWD = "postgres";

    public static Connection getConnection() throws SQLException, ClassNotFoundException
    {
        BufferedReader br = null;
        if (MY_URL.contains("?"))
        {
            try {

                File file = new File("/home/pos/Scrivania/uniconfig.txt");
                br = new BufferedReader(new FileReader(file));
                String ip = br.readLine();

                MY_URL = MY_URL.replace("?", ip);

            } catch (FileNotFoundException ex) {
                conn = null;
            } catch (IOException ex) {
                Logger.getLogger(UniConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    br.close();
                } catch (IOException ex) {
                    Logger.getLogger(UniConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if (conn == null) {
            Class.forName(MY_DRIVER);
            conn = DriverManager.getConnection(MY_URL,
                    LOGIN, PASSWD);
        } else if (conn.isClosed())
            conn = DriverManager.getConnection(MY_URL,
                    LOGIN, PASSWD);
        else
            conn.rollback();

        return conn;
    }
}